<template>
<div>
	<Card  dis-hover>
		<p slot="title">订单商品</p>
		<p pd2>
			<Dropdown @on-click="handleBatchClick">
				<Button size="small">
					<span>批量操作</span>
					<Icon type="ios-arrow-down"></Icon>
				</Button>
				<DropdownMenu slot="list">
					<DropdownItem name="ship" :disabled="selectedCanShipItems.length==0">批量订单发货</DropdownItem>
					<DropdownItem name="finish" :disabled="selectedItems.length==0">批量订单完成</DropdownItem>
					<DropdownItem name="delete" :disabled="selectedItems.length==0">批量订单删除</DropdownItem>
				</DropdownMenu>
			</Dropdown>
		</p>
		<p pd1 bd-gray4 bg-gray5>
			<Select v-model="searchModel.searchTarget" size="small" w6>
				<Option value="orderNumber">订单编号</Option>
				<Option value="userName">会员</Option>
				<Option value="phoneNumber">收货手机号</Option>
				<Option value="subject">产品名称</Option>
			</Select>
			<Input v-model="searchModel.search" size="small" w8 mgr2 />
			<Button size="small" @click="handleSearch">查询</Button>
		</p>
		<p pd1 mgt2>
			<RadioGroup v-model="searchModel.status" type="button" size="small" @on-change="handleSearch">
				<Radio label="all">所有订单</Radio>
				<Radio label="pendingPay">待付款</Radio>
				<Radio label="pendingShip">待发货</Radio>
				<Radio label="shipped">已发货</Radio>
				<Radio label="pendingFinish">待结算</Radio>
				<Radio label="finished">交易完成</Radio>
				<Radio label="closed">交易关闭</Radio>
			</RadioGroup>
		</p>
		<table class="minitable" long>
			<tr text-center bg-gray5>
				<td text-left>
					<Checkbox v-model="isSelectAll" @on-change="handleSelectAll"/>
					<span>订单信息</span>
				</td>
				<td w5>单价(元)</td>
				<td w5>数量</td>
				<td w6>买家</td>
				<td w6>订单金额</td>
				<td w7>交易状态</td>
				<td w6>操作</td>
			</tr>
		</table>

		<table border="0" cellspacing="0" cellpadding="0" class="minitable" v-for="(item, index) in items" :key="index" long mgt2>
			<tr>
				<td colspan="7" bg-gray5>
					<Checkbox v-model="item.selected" @on-change="handleSelectItem" />
					<span mgr3>订单号：{{item.orderNumber}}</span>
					<span>交易时间：{{formatTimeStr(item.info.creationTime)}}</span>
				</td>
			</tr>
			<tr text-center>
				<td text-left nopd>
					<table border="0" cellspacing="0" cellpadding="0" class="minitable-child" long>
						<tr v-for="(item2, index2) in item.details" :key="index2">
							<td pd2>
								<div h4 w4 bd-gray4 left mgr2 bg-cover :style="{'background-image':`url(${item2.commodityPicture})`}"></div>
								<p sz1>{{item2.commodityName}}</p>
								<p gray2>
									<span v-for="(value, key) in item2.shoppingOptionParameters" :key="key" mgr1>{{value}}</span>
								</p>
							</td>
							<td text-center w5>x{{item2.price}}</td>
							<td text-center w5>{{item2.count}}</td>
						</tr>
					</table>
				</td>
				<td w6>{{item.memberInfo.userName}}</td>
				<td w6>
					<p>{{formatPrice(item.info.totalAmount)}}</p>
					<p v-if="item.info.xpAmount+item.info.couponAmount" gray3>优惠：{{formatPrice(item.info.xpAmount+item.info.couponAmount)}}</p>
					<p v-if="item.info.adjustmentAmount!=0" gray3>调整：{{formatPrice(item.info.adjustmentAmount)}}</p>
				</td>
				<td w7>{{getOrderStatus(item)}}</td>
				<td w6>
					<p linkable blue @click="handleShowOrderDetailModal(item)">查看详情</p>
					<p v-if="canModifyOrder(item)" @click="handleShowOrderUpdateModal(item)" linkable blue>修改订单</p>
					<p v-if="canShipOrder(item)" @click="handleShowShipModal(item.orderNumber)" linkable blue>订单发货</p>
					<p v-if="canConfirmPayment(item)" @click="handleShowConfirmPaymentModal(item.orderNumber)" linkable blue>确认收款</p>
					<p v-if="canFinishOrder(item)" @click="handleFinishOrder(item.orderNumber, handleSearch)" linkable blue>订单完成</p>
					<p v-if="canDeleteOrder(item)" @click="handleDeleteOrder(item.orderNumber, handleSearch)" linkable blue>删除订单</p>
				</td>
			</tr>
		</table>
		
    	<AutoPage :value="page" :auto="false" text-right mgt2></AutoPage>
	</Card>

	<Modal v-model="batchShip.showModal" title="批量订单发货" width="75" :mask-closable="false">
		<table class="minitable" long>
			<tr bg-gray5>
				<td>订单编号</td>
				<td>商品信息</td>
				<td>物流公司</td>
				<td>运单号码</td>
			</tr>
			<tr v-for="(item, index) in batchShip.items" :key="index">
				<td>{{item.orderNumber}}</td>
				<td>{{item.subject}}</td>
				<td>
					<Select v-model="item.expressType" size="small" long>
						<Option v-for="(name, key) in expresses" :key="key" :value="key">{{name}}</Option>
					</Select>
				</td>
				<td><Input v-model="item.number" size="small" /></td>
			</tr>
		</table>
        <div slot="footer">
            <Button type="primary" @click="handleBatchShip">批量发货</Button>
            <Button @click="batchShip.showModal=false">取消</Button>
        </div>
	</Modal>

	<Modal v-model="confirmPayment.showModal" title="确认收款" :mask-closable="false">
		<Form ref="order-confirmpayment" :model="confirmPayment.model" :label-width="100">
			<FormItem label="订单号" prop="orderNumber">
				<Input v-model="confirmPayment.model.orderNumber" disabled />
			</FormItem>
			<FormItem label="支付类型" prop="paymentType" required>
				<Select v-model="confirmPayment.model.paymentType" w7 mgr2>
					<Option :value="0">在线支付</Option>
					<Option :value="1">货到付款</Option>
					<Option :value="2">银行转账</Option>
				</Select>
				<Select v-if="confirmPayment.model.paymentType==0" v-model="confirmPayment.model.paymentMethod" w7>
					<Option :value="0">支付宝</Option>
					<Option :value="1">微信</Option>
				</Select>
			</FormItem>
			<FormItem label="支付单号" prop="tradeNumber">
				<Input v-model="confirmPayment.model.tradeNumber" />
			</FormItem>
			<FormItem label="备注信息" prop="remark">
				<Input v-model="confirmPayment.model.remark" type="textarea" :rows="4" />
			</FormItem>
		</Form>
        <div slot="footer">
            <Button type="primary" @click="handleConfirmPayment">确认收款</Button>
            <Button @click="confirmPayment.showModal=false">取消</Button>
        </div>
	</Modal>

	<Modal v-model="ship.showModal" title="订单发货" :mask-closable="false">
		<Form ref="order-ship" :model="ship.model" :label-width="100">
			<FormItem label="物流信息" prop="wuliuType">
				<RadioGroup v-model="ship.model.wuliuType">
					<Radio label="0">默认</Radio>
					<Radio label="1">自定义</Radio>
				</RadioGroup>
			</FormItem>
			<div v-if="ship.model.wuliuType==0">
				<FormItem label="物流公司" prop="expressType">
					<Select v-model="ship.model.expressType" long>
						<Option v-for="(name, key) in expresses" :key="key" :value="key">{{name}}</Option>
					</Select>
				</FormItem>
				<FormItem label="运单号码" prop="number" required>
					<Input v-model="ship.model.number" />
				</FormItem>
			</div>
			<div v-else>
				<FormItem prop="customWuliuInfo">
					<Input v-model="ship.model.customWuliuInfo" type="textarea" :rows="4" />
				</FormItem>
			</div>
		</Form>
        <div slot="footer">
            <Button type="primary" @click="handleShipOrder">保存发货信息</Button>
            <Button @click="ship.showModal=false">取消</Button>
        </div>
	</Modal>

	<Modal v-model="orderDetail.showModal" title="订单详情" width="80">
        <order-detail v-if="orderDetail.showModal" :order="orderDetail.order"></order-detail>
    </Modal>

	<order-update v-model="orderUpdate.showModal" :order="orderUpdate.order" @save-success="handleSearch"></order-update>
</div>
</template>

<script lang="ts">
import { Component, Vue,Inject, Prop,Watch } from 'vue-property-decorator';
import OrderBase from './OrderBase';
import AutoPage from '@common/components/AutoPage';
import Page from '@common/models/Page';
import OrderDetail from './order-detail.vue'
import OrderUpdate from './order-update.vue'

@Component({
	components:{ AutoPage, OrderDetail, OrderUpdate }
})
export default class OrderManager extends OrderBase {
	isSelectAll:Boolean = false;
	batchShip = {
		showModal: false,
		items: []
	}
	confirmPayment = {
		showModal: false,
		model: {
			orderNumber: "",
			paymentType: 0,
			paymentMethod: 0,
			tradeNumber: "",
			remark: ""
		}
	}
	ship = {
		showModal: false,
		model: {
			orderNumber: "",
			wuliuType: "0",
			customWuliuInfo: "",
			number: "",
			expressType: "",
			expressName: "",
		}
	}
	orderDetail = {
		showModal: false,
		order: null
	}
	orderUpdate = {
		showModal: false,
		order: null
	}
	searchModel:any = {
		search: '',
		searchTarget: 'orderNumber',
		status: 'all'
	}
	page:Page = new Page('/api/services/app/AdminOrderManager/Search')
	items:Array<any> = []
	get selectedItems() {
		return this.items.reduce((result, elem) => {
			if(elem.selected) result.push(elem);
			return result;
		}, []);
	}
	get selectedCanShipItems() {
		var temp = this.items.reduce((result, elem) => {
			if(elem.selected && this.canShipOrder(elem)) result.push(elem);
			return result;
		}, []);
		this.batchShip.items = temp.map(elem => {
			return {
				orderNumber: elem.orderNumber,
				subject: elem.info.subject,
				number: "",
				expressType: ""
			}
		});
		return temp;
	}
	handleSelectAll(value) {
		this.items.forEach(elem => {
			elem.selected = value;
		});
	}
	handleSelectItem(value) {
		for(var i = 0; i < this.items.length; i++) {
			var elem = this.items[i];
			if(elem.selected == false){
				this.isSelectAll = false;
				return;
			}
		}
		this.isSelectAll = true;
	}
	handleSearch() {
		this.page.action_data = this.searchModel;
		this.page.getData(async () => {
			this.items = this.page.items.map(elem => {
				return Object.assign({ selected: false }, elem);
			});
			await this.$store.dispatch('member/getMemberProfiles', this.page.items.map(elem => elem.memberInfo.id));
		});
	}
	// 批量处理
	handleBatchClick(name) {
		var count = this.selectedItems.length;
		var orderNumbers = this.selectedItems.map(elem => elem.orderNumber);

		switch(name) {
			case 'ship': 
				if(this.selectedCanShipItems.length == 0) {
					this.error('未选择可以发货的订单');
					break;
				}
				this.batchShip.showModal = true; break;
			case 'finish': this.confirm(`确认批量完成选中的${count}个订单吗？`, async () => {
				var response = await this.post('AdminOrderManager/SetFinish', { orderNumbers: orderNumbers });
				if(response.success) {
					this.success('批量完成订单成功');
					this.handleSearch();
				}
			}); break;
			case 'delete': this.confirm(`确认批量删除选中的${count}个订单吗？`, async () => {
				var response = await this.post('AdminOrderManager/Delete', { orderNumbers: orderNumbers });
				if(response.success) {
					this.success('批量删除订单成功');
					this.handleSearch();
				}
			}); break;
		}
	}
	async handleBatchShip() {
		for(var i = 0; i < this.batchShip.items.length; i++) {
			var item = this.batchShip.items[i];
			if(item.number == '') {
				this.error('必须填写运单号码');
				return;
			}
		}
		var response = await this.post('AdminOrderManager/SetShippedBatch', { items: this.batchShip.items });
		if(response.success) {
			this.success('批量发货成功');
			this.batchShip.showModal = false;
			this.handleSearch();
		}
	}
	// 确认支付
	handleShowConfirmPaymentModal(orderNumber) {
		this.confirmPayment.model = {
			orderNumber: orderNumber,
			paymentType: 0,
			paymentMethod: null,
			tradeNumber: "",
			remark: ""
		};
		this.confirmPayment.showModal = true;
	}
	handleConfirmPayment() {
		(this.$refs["order-confirmpayment"] as any).validate(async (valid) => {
			if(valid) {
				var response = await this.post('AdminOrderManager/ConfirmPayment', this.confirmPayment.model);
				if(response.success) {
					this.confirmPayment.showModal = false;
					this.handleSearch();
				}
			}
		});
	}
	// 订单发货
	handleShowShipModal(orderNumber) {
		this.ship.model = {
			orderNumber: orderNumber,
			wuliuType: "0",
			customWuliuInfo: "",
			number: "",
			expressType: "",
			expressName: "",
		};
		this.ship.showModal = true;
	}
	async handleShipOrder() {
		(this.$refs["order-ship"] as any).validate(async (valid) => {
			if(valid) {
				this.ship.model.expressName = this.expresses[this.ship.model.expressType];
				var response = await this.post('AdminOrderManager/SetShipped', this.ship.model);
				if(response.success) {
					this.ship.showModal = false;
					this.handleSearch();
				}
			}
		});
	}
	// 订单详情
	handleShowOrderDetailModal(order) {
		this.orderDetail.order = order;
		this.orderDetail.showModal = true;
	}
	// 更新订单
	handleShowOrderUpdateModal(order) {
		this.orderUpdate.order = order;
		this.orderUpdate.showModal = true;
	}
	created() {
		this.handleSearch();
	}
}
</script>